<?php

class AtividadeController extends Controller {

    /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
    public function accessRules() {
        return array(
            array('allow', // allow authenticated user to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('create', 'update', 'delete', 'conclude'),
                'expression' => '$user->isOperator()',
            ),
            array('deny',  // deny all users
                'users' => array('*'),
                'message' => 'Você não está autorizado a entrar nesta página.'
            ),
        );
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {
        $this->render('view', array('model' => $this->loadModel($id)));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {
        $model = new Atividade;

        if(isset($_POST['Atividade'])) {
            $model->attributes = $_POST['Atividade'];
            $model->id_usuario = Yii::app()->user->id;
            $model->data = DateHelper::changeDateFormatToSql($model->data);

            //This is necessary to guarantee that model and attachments are salved only together
            $transaction = Yii::app()->db->beginTransaction();
            try {
                if($model->save()) {
                    $this->saveAttachments($model->id_atividade);
                    $this->setMessage('Atividade cadastrada com sucesso.');
                    $this->setWebSocketUpdate();

                    $transaction->commit();

                    $this->redirect(array('index'));
                }
                else
                    $this->setMessage('Atividade não pôde ser cadastrada.');
            }
            catch(Exception $e) {
                $transaction->rollback();
                $this->setMessage('Atividade não pôde ser cadastrada.');
            }
        }

        $this->render('form', array(
            'model' => $model,
            'instalacoes' => Instalacao::model()->findAll(array('select' => 'id_instalacao, acronimo'))
        ));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
        $model = $this->loadModel($id);

        if(isset($_POST['Atividade'])) {
            $model->attributes = $_POST['Atividade'];
            $model->data = DateHelper::changeDateFormatToSql($model->data);

            //This is necessary to guarantee that model and attachments are salved/deleted only together
            $transaction = Yii::app()->db->beginTransaction();
            try {
                $this->saveAttachments($model->id_atividade);
                $this->deleteSelectedAttachments();

                if($model->save()) {
                    $this->setMessage('Atividade atualizada com sucesso.');
                    $this->setWebSocketUpdate();

                    $transaction->commit();

                    $this->redirect(array('index'));
                }
                else
                    $this->setMessage('Atividade não pôde se atualizada.');
            }
            catch(Exception $e) {
                $transaction->rollback();
                $this->setMessage('Atividade não pôde se atualizada.');
            }
        }

        $this->render('form', array(
            'model' => $model,
            'instalacoes' => Instalacao::model()->findAll(array('select' => 'id_instalacao, acronimo'))
        ));
	}

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     * @throws CHttpException
     */
    public function actionDelete($id) {
        //The action delete is given by ajax, then just remove or throw exception
        $transaction = Yii::app()->db->beginTransaction();
        try {
            Anexo::model()->deleteAllByAttributes(array('id_atividade' => $id));

            if(!Atividade::model()->deleteByPk($id))
                throw new CHttpException(403, 'Atividade não pôde ser excluída.');

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollback();
        }
	}

	/**
	 * Lists all models
	 */
	public function actionIndex() {
        $model = new Atividade('index');
        $model->unsetAttributes();  // clear any default values

        if(isset($_GET['Atividade']))
            $model->attributes = $_GET['Atividade'];

        $this->render('index', array(
            'model' => $model,
            'datas' => Atividade::model()->findAll(array(
                    'select' => 'data',
                    'condition' => 'concluida = ' . ConclusionTypes::NOT_CONCLUDED)),
            'acronimos' => Instalacao::model()->findAll(array('select' => 'acronimo')),
            'centros_de_operacao_e_orgaos' => Usuario::model()->findAll(array(
                    'select' => 'centro_de_operacao, orgao',
                    'condition' => 'centro_de_operacao <> "" OR orgao <> ""')),
        ));
	}

    /**
     * Conclude a activity given by id
     * @param $id
     */
    public function actionConclude($id) {
        $atividade = $this->loadModel($id);

        $atividade->classifyActivityConcluded();
        if($atividade->update(array('concluida'))) {
            $this->setMessage('Atividade concluída com sucesso.');
            $this->setWebSocketUpdate();
        }
        else
            $this->setMessage('Atividade não pôde ser concluída.');

        $this->actionIndex();
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Atividade the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id) {
        $model = Atividade::model()->with('Usuario', 'Instalacao', 'Anexo')->findByPk($id);

        if($model === null)
            throw new CHttpException(404, 'A página requisitada não existe.');

        return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Atividade $model the model to be validated
	 */
	protected function performAjaxValidation($model) {
        if(isset($_POST['ajax']) && $_POST['ajax'] === 'atividade-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
	}

    /**
     * Get uploaded files and save them on database
     * @param $id_atividade
     * @throws CHttpException
     * @return void
     */
    private function saveAttachments($id_atividade) {
        $anexos = CUploadedFile::getInstancesByName('anexos');

        if (isset($anexos) && count($anexos) > 0) {
            $attachment = new Anexo();

            foreach ($anexos as $index => $file) {
                $uniqueName = sprintf('usuario-%d-data-%s-%s', Yii::app()->user->id, date('d-m-H-i-s'), $file->name);
                if ($file->saveAs(sprintf('%s%s', $attachment->getPath(), $uniqueName))) {
                    $attachment->nome = $file->name;
                    $attachment->link = $uniqueName;
                    $attachment->id_atividade = $id_atividade;
                    $attachment->save();
                }
                else
                    throw new CHttpException(403, 'Anexo não pôde ser salvo.');
            }
        }
    }

    /**
     * Delete selected files from database
     * @throws CHttpException
     */
    private function deleteSelectedAttachments() {
        $idsString = $_POST['file_ids_to_remove'];
        $ids = explode(',', $idsString);

        if(!is_null($ids) && is_int($ids[0]))
            foreach ($ids as $index => $id)
                if(!Anexo::model()->deleteByPk($id))
                    throw new CHttpException(403, 'Anexo não pôde ser excluído.');
    }

    /**
     * Sets WebSocket message to send to other WebSocket clients
     */
    private function setWebSocketUpdate() {
        Yii::app()->user->setFlash('websocket', sprintf('Operador %s: Atualizar página.', Yii::app()->user->getFullName()));
    }

    /**
     * Sets message to be shown on view
     * @param $message
     */
    private function setMessage($message) {
        Yii::app()->user->setFlash('message', $message);
    }
}
